﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Helper;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using NPOI.SS.Formula;
using NPOI.SS.UserModel;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DFGK_WMS.Repository
{
    /// <summary>
    /// 盘点单管理
    /// </summary>
    public class TStocktakingOrderRepository : BaseRepository<TStocktakingOrder>, ITStocktakingOrderRepository
    {
        public TStocktakingOrderRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }
        /// <summary>
        /// 导出盘点单号
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TStocktakingOrder> GetStockingExcel()
        {
            try
            {
                #region 弃用
                //var alist = Context.TStocktakingOrders.AsQueryable();//盘点单
                //var blist=Context.TMaterials.AsQueryable();//物料
                //var clist=Context.TAreas.AsQueryable();//库区
                //var dlist=Context.TWarehouses.AsQueryable();//库房
                //var query = from a in alist
                //            join b in blist
                //            on a.MaterialId equals b.Id
                //            join c in clist
                //            on a.AreaId equals c.Id
                //            join d in dlist
                //            on a.WarehouseId equals d.Id
                //            select new TStocktakingOrderDto
                //            {
                //                Name=a.Name,
                //                FName=d.Name,
                //                KName=c.Name,
                //                WName=b.Name,
                //                BillType=a.BillType,
                //                PlanType=a.PlanType,
                //                StocktakeWay= a.StocktakeWay,
                //                BatchNo = a.BatchNo,
                //                CreateUserName = a.CreateUserName,
                //                CreateDate = a.CreateDate

                //            };
                //return query.ToList();
                #endregion
                var slist=Context.TStocktakingOrders.ToList();
                return slist;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool AddStocktakingOrder(TStocktakingOrderDto dto,out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                message = "";
                try
                {
                    TStocktakingOrder order = new TStocktakingOrder();
                    order = Mapper.Map<TStocktakingOrder>(dto);
                    //库房
                    var wobj = Context.TWarehouses.Find(dto.WarehouseId);
                    if(wobj!=null && wobj.Status==1)
                    {
                        order.WarehouseName = wobj.Name;
                        order.WarehouseCode = wobj.Code;
                    }
                    else
                    {
                        message = "库房不存在或已被禁用！";
                        return false;
                    }
                    //库区
                    var aobj = Context.TAreas.Find(dto.AreaId);
                    if (aobj!=null && aobj.Status==1)
                    {
                        order.AreaName = aobj.Name;
                        order.AreaCode = aobj.Code;
                    }
                    else
                    {
                        message = "库区不存在或已被禁用！";
                        return false;
                    }
                    //状态默认为创建
                    order.Status = 0;
                    //盘点计划默认为普通抽盘
                    order.PlanType = 10;
                    //订单明细的数量
                    order.FinishedCount = dto.Inventorys.Count;
                    order.CreateDate = DateTime.Now;
                    order.CreateUserId = dto.NowUserId;
                    order.CreateUserName = dto.NowUserRealName;
                    Context.TStocktakingOrders.Add(order);
                    Context.SaveChanges();

                    foreach (var item in dto.Inventorys)
                    {
                        TStocktakingOrderDetail m = new TStocktakingOrderDetail();
                        m.OrderId = order.Id;
                        m.OrderSn = order.OrderSn;
                        m.CellId = item.LocationId;
                        m.CellCode = item.LocationCode;
                        m.CellDepthIndex = item.LocationDepth;
                        m.PalletBarcode = item.PalletBarcode;
                        m.Status = (int)item.Status;
                        m.MaterialId = item.MaterialId;
                        m.MaterialName = item.MaterialName;
                        m.MaterialCode = item.MaterialCode;
                        m.CreateDate = DateTime.Now;
                        m.HasSkuDetail = item.HasSkuDetail;
                        m.Qty = item.AvailableQty;
                        m.QualityState = item.QualityState;
                        m.BatchNo = item.BatchNo;
                        m.OwnerId = item.OwnerId;
                        m.OwnerName = item.OwnerName;
                        m.ExpireDate = item.ExpireDate;
                        m.ProductDate = item.ProductDate;
                        m.SupplierId = item.SupplierId;
                        m.SupplierName = item.SupplierName;
                        m.MaterialTypeId = item.MaterialTypeId;
                        m.MaterialTypeName = item.MaterialTypeName;
                        m.InventoryId = item.Id;
                        m.WarehouseId = item.WarehouseId;
                        Context.TStocktakingOrderDetails.Add(m);
                        Context.SaveChanges();
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }


        /// <summary>
        /// 创建PdA上的盘点单
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="message"></param>
        /// <returns></returns>
      /* public bool  AddPdApandian(TInventorymaterialdetailsdto
       * dto,out string message)
        {

            
            using (var shiwu=Context.Database.BeginTransaction())
            {
                message = "";
                try
                {
                    var plan = Context.TStocktakingPlans.FirstOrDefault(p => p.Id == dto.planId);
                    var pandianjihuaid = Context.TStocktakingPlans.Find(plan.Id);               //关联的盘点计划id        
                    if (plan != null)
                    {
                        throw new Exception("已有盘点单号");
                    }
                    TStocktakingOrder pandianliebiao=new TStocktakingOrder();
                    pandianliebiao = Mapper.Map<TStocktakingOrder>(dto);
                    //添加库房
                    var kufang = Context.TWarehouses.FirstOrDefault(x=>x.Name==dto.deptName);
                    pandianliebiao.MaterialName=dto.materialName;//物料名称
                    pandianliebiao.BatchNo = dto.batch;//批次号
                                                       //物资编码
                                                       //规格型号
                  
                    pandianliebiao.OrderSn=dto.planNumber

                }
                catch (Exception)
                {

                    throw;
                }

            }
        }*/

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool UpdateStocktakingOrder(TStocktakingOrderDto dto,out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                message = "";
                try
                {
                    TStocktakingOrder order = new TStocktakingOrder();
                    order = Mapper.Map<TStocktakingOrder>(dto);
                    //库房
                    var wobj = Context.TWarehouses.Find(dto.WarehouseId);
                    if (wobj != null && wobj.Status==1)
                    {
                        order.WarehouseName = wobj.Name;
                        order.WarehouseCode = wobj.Code;
                    }
                    else
                    {
                        message = "库房不存在或已被禁用！";
                        return false;
                    }
                    //库区
                    var aobj = Context.TAreas.Find(dto.AreaId);
                    if (aobj != null && aobj.Status==1)
                    {
                        order.AreaName = aobj.Name;
                        order.AreaCode = aobj.Code;
                    }
                    else
                    {
                        message = "库区不存在或已被禁用！";
                        return false;
                    }
                    order.CreateDate = dto.CreateDate;
                    order.CreateUserId = dto.CreateUserId;
                    order.CreateUserName = dto.CreateUserName;
                    order.FinishedCount = dto.Inventorys.Count;
                    order.ModifyDate = DateTime.Now;
                    order.ModifyUserId = dto.NowUserId;
                    order.ModifyUserName = dto.NowUserRealName;
                    Context.TStocktakingOrders.Update(order);
                    Context.SaveChanges();

                    var slist = Context.TStocktakingOrderDetails.Where(x => x.OrderId == order.Id && x.OrderSn == order.OrderSn);
                    if(slist!=null || slist.Any())
                    {
                        Context.TStocktakingOrderDetails.RemoveRange(slist);
                        Context.SaveChanges();
                    }
                    foreach (var item in dto.Inventorys)
                    {
                        TStocktakingOrderDetail m = new TStocktakingOrderDetail();
                        m.OrderId = order.Id;
                        m.OrderSn = order.OrderSn;
                        m.CellId = item.LocationId;
                        m.CellCode = item.LocationCode;
                        m.CellDepthIndex = item.LocationDepth;
                        m.PalletBarcode = item.PalletBarcode;
                        m.Status = (int)item.Status;
                        m.MaterialId = item.MaterialId;
                        m.MaterialName = item.MaterialName;
                        m.MaterialCode = item.MaterialCode;
                        m.CreateDate = DateTime.Now;
                        m.HasSkuDetail = item.HasSkuDetail;
                        m.Qty = item.AvailableQty;
                        m.QualityState = item.QualityState;
                        m.BatchNo = item.BatchNo;
                        m.OwnerId = item.OwnerId;
                        m.OwnerName = item.OwnerName;
                        m.ExpireDate = item.ExpireDate;
                        m.ProductDate = item.ProductDate;
                        m.SupplierId = item.SupplierId;
                        m.SupplierName = item.SupplierName;
                        m.MaterialTypeId = item.MaterialTypeId;
                        m.MaterialTypeName = item.MaterialTypeName;
                        m.InventoryId = item.Id;
                        m.WarehouseId = item.WarehouseId;
                        Context.TStocktakingOrderDetails.Add(m);
                        Context.SaveChanges();
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DelStocktakingOrder(int ids)
        {
            try
            {
                //盘点单
                var del = Context.TStocktakingOrders.Find(ids);
                Context.TStocktakingOrders.Remove(del);
                //盘点单明细
                var slis = Context.TStocktakingOrderDetails.Where(x => x.OrderId == ids);
                if(slis.Any())
                {
                    Context.TStocktakingOrderDetails.RemoveRange(slis);
                }
                return Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="aid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<TStocktakingOrder> GetStocktakingOrders(int wid,int aid,string name, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var list = Context.TStocktakingOrders.AsQueryable();
                if(wid!=0)
                {
                    list = list.Where(x => x.WarehouseId == wid);
                }
                if(aid!=0)
                {
                    list = list.Where(x => x.AreaId == aid);
                }
                
                totalCount = list.Count();
                list = list.OrderByDescending(x=>x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                
                return list.ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public TStocktakingOrderDto GetStocktakingOrder(int ids)
        {
            var tsobj = Context.TStocktakingOrders.Find(ids);
            TStocktakingOrderDto m = new TStocktakingOrderDto();
            if (tsobj!=null)
            {
                
                m = Mapper.Map<TStocktakingOrderDto>(tsobj);

                var tsoobj = Context.TStocktakingOrderDetails.Where(x => x.OrderId == tsobj.Id);
                if(tsoobj.Any())
                {
                    List<TInventory> inventories = new List<TInventory>();
                    foreach (var item in tsoobj)
                    {
                        TInventory inventory = new TInventory();
                        inventory = Mapper.Map<TInventory>(item);
                        inventory.AvailableQty=item.Qty;
                        inventory.LocationId = item.CellId;
                        inventory.LocationCode = item.CellCode;
                        inventory.LocationDepth = (int)item.CellDepthIndex;
                        inventory.Id = (int)item.InventoryId;
                        inventories.Add(inventory);
                    }
                    //弃用
                    //var ilist = tsoobj.Select(x => new TInventory
                    //{  
                       
                    //    PalletBarcode = x.PalletBarcode,
                    //    Status = x.Status,
                    //    MaterialId = x.MaterialId,
                    //    MaterialName = x.MaterialName,
                    //    MaterialCode = x.MaterialCode,
                    //    CreateDate = x.CreateDate,
                    //    HasSkuDetail = (bool)x.HasSkuDetail,
                    //    AvailableQty = x.Qty,
                    //    QualityState = x.QualityState,
                    //    BatchNo = x.BatchNo,
                    //    OwnerId = x.OwnerId,
                    //    OwnerName = x.OwnerName,
                    //    ExpireDate = x.ExpireDate,
                    //    ProductDate = x.ProductDate,
                    //    SupplierId= x.SupplierId,
                    //    SupplierName = x.SupplierName,
                    //    MaterialTypeId = x.MaterialTypeId,
                    //    MaterialTypeName = x.MaterialTypeName,
                    //    Id = (int)x.InventoryId,
                    //    WarehouseId= x.WarehouseId,
                    //});
                    m.Inventorys = inventories;
                }
            }
            return m;
            
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdTStocktakingOrderState(ReceivingOrderDetailDto m,out string message)
        {
            var robj = Context.TStocktakingOrders.Find(m.Id);

            if (robj != null)
            {            
                switch (robj.Status)
                {
                    case 0:
                        var uobj = Context.TUsers.FirstOrDefault(x => x.Id == m.NowUserId && x.JobNo == m.JobNo);
                        if (uobj != null)
                        {
                            robj.SubmitUserId = m.NowUserId;
                            robj.SubmitUserName = m.NowUserRealName;
                            robj.SubmitDate = DateTime.Now;
                            robj.Remark = m.Remark;
                            //修改为：审核通过
                            robj.Status = 2;
                            Context.TStocktakingOrders.Update(robj);
                            break;
                        }
                        message = "工号有误！";
                        return false;

                    case 1:
                        break;

                    case 2:                
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：作业中
                        robj.Status = 3;
                        Context.TStocktakingOrders.Update(robj);
                        break;

                    case 3:
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：已完成
                        robj.Status = 4;
                        Context.TStocktakingOrders.Update(robj);
                        break;

                    default:
                        break;
                }
                message = "修改成功！";
                return Context.SaveChanges() > 0;
            }
            message = "修改失败！";
            return false;
        }
        /// <summary>
        /// 修改盘点pda信息
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool UpdatePdaxiugaizhuangtai(List<TInventorymaterialdetailsdto> dto, int planid, string plannumber, out string message,int userid)
        {
            var robj = Context.TStocktakingOrderDetails.FirstOrDefault(x=>x.OrderSn==plannumber);
            try
            {
                using (var reader=Context.Database.BeginTransaction())
                {
                    if (robj != null)
                    {
                        switch (robj.Status)
                        {
                            case 0:
                                var uobj = Context.TStocktakingOrders.Where(x => x.planId == robj.OrderId && x.Status ==0);
                                if (uobj != null)
                                {
                                    foreach (var item in dto)
                                    {
                                        var jihua = Context.TStocktakingOrders.Where(x => x.MaterialName == item.materialName && x.PlanType == item.storeLocationId&&x.planId==planid).FirstOrDefault();
                                        if (jihua != null)
                                        {
                                            //jihua.materialCode = item.materialCode;
                                            jihua.Status = 1;
                                            jihua.qualityStatus = item.qualityStatus;

                                            jihua.FinishedCount = item.checkAmount;
                                            decimal a = jihua.CellCount - item.checkAmount;
                                            int zhngshu=Math.Abs(Convert.ToInt32(a));
                                            if (a == 0)
                                            {
                                                jihua.MyProperty = zhngshu;
                                            
                                            }
                                            else if (a < 0)
                                            {
                                                jihua.MyProperty = zhngshu;
                                      
                                            }
                                            else if (a > 0)
                                            {
                                                jihua.MyProperty = zhngshu;
                                    
                                            }

                                            jihua.CreateUserId = item.supervisorId;
                                            //修改为：审核通过
                                            jihua.SubmitUserId = item.userId;
                                            jihua.Remark = item.checkResult;
                                            Context.TStocktakingOrders.Update(jihua);
                                            Context.SaveChanges();
                                            if (jihua.Status == 1)
                                            {
                                                robj.InventoryId = item.supervisorId;
                                                robj.WarehouseId = item.userId;
                                                robj.Status = 1;
                                                robj.ExpectedStationIds = "待执行";
                                                Context.TStocktakingOrderDetails.Update(robj);
                                                Context.SaveChanges();
                                                //using (var reades=Context.Database.BeginTransaction())
                                                //{

                                                //}
                                            }
                                            //if (jihua.Status!=0)
                                            //{
                                            //    Context.TStocktakingOrderDetails.Update(uobj);
                                            //}
                                        }
                                      
                                    }

                                    message = "修改成功！";
                                   
                                    //uobj.Status = 1;
                                    //uobj.FinishedCount = dto.checkAmount;
                                    //decimal a = uobj.CellCount - dto.checkAmount;
                                    //if (a==0)
                                    //{
                                    //    uobj.MyProperty = a;
                                    //    uobj.qualityStatus = 1;
                                    //}
                                    //else if (a<0)
                                    //{
                                    //    uobj.MyProperty = a;
                                    //    uobj.qualityStatus = 2;
                                    //}
                                    //else if (a>0)
                                    //{
                                    //    uobj.MyProperty = a;
                                    //    uobj.qualityStatus = 3;
                                    //}

                                    //uobj.CreateUserId = dto.supervisorId;
                                    ////修改为：审核通过
                                    //uobj.SubmitUserId= dto.planId;
                                    //uobj.Remark = dto.checkResult;
                                    //Context.TStocktakingOrders.Update(uobj);

                                    reader.Commit();

                                    break;
                                    
                                }
                                message = "工号有误！";
                                return false;

                            case 1:
                                break;


                            default:
                                break;
                        }
                        message = "修改成功！";
                        return true;
                    }
                    message = "修改失败！";
                    return false;
                }
             
            }
            catch (Exception)
            {

                throw;
            }
           
        }
        /// <summary>
        /// 根据库房库区查询库存表
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="aid"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TInventory> GetWhArList(int? wid, int? aid, string name, int pageIndex, int pageSize, out int totalCount)
        {
            var ilist = Context.TInventory.Where(x => x.WarehouseId == wid);
            if(ilist.Any())
            {
                if(aid!=0)
                {
                    ilist = ilist.Where(x => x.AreaId == aid);
                }

                if(!string.IsNullOrEmpty(name))
                {
                    ilist = ilist.Where(x => x.MaterialName.Contains(name));
                }
                totalCount = ilist.Count();
                ilist = ilist.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return ilist.ToList();
            }
            totalCount = 0;
            return ilist.ToList();
        }
        /// <summary>
        /// 查询pda上全部盘点单的信息
        /// </summary>
        /// <param name="planId"></param>
        /// <param name="OrderSn"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalcount"></param>
        /// <returns></returns>

        public List<TStocktakingOrder> GetPDApandianlist(long? planId, string? OrderSn, int pageindex, int pagesize,out int totalcount)
        {
            var list=Context.TStocktakingOrders.AsNoTracking().AsQueryable().OrderByDescending(x=>x.CreateDate).Skip((pageindex-1)*pagesize).Take(pagesize);
            totalcount= list.Count();
            if (!string.IsNullOrEmpty(OrderSn))
            {
                list = list.Where(n => n.OrderSn == OrderSn);
            }
            if (planId!=null)
            {
                list=list.Where(n=>n.planId==planId);   
            }
            return list.ToList();
        }

        public object GetPDAlistyi()
        {
            //var list = Context.TStocktakingOrders.AsNoTracking();
            //if (planid!=null)
            //{
            //    list.Where(x => x.planId == planid);
            //}
            //list = list.FirstOrDefault();
            //return list.ToList();


            try
            {
                int dd = 3;
                int c = 5;
                //string uname = HttpContext.User.FindFirstValue("UserName");
                //string runame = HttpContext.User.FindFirstValue("RealName");
                //int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                var alist = Context.TStocktakingOrders.AsQueryable();//盘点单
                var blist = Context.TStocktakingOrderDetails.AsQueryable();//盘点订单id
                var clist = Context.TAreas.AsQueryable();//库区
                var dlist = Context.TWarehouses.AsQueryable();//库房

                var query = from a in blist
                          
                            where a.Status==1
                            select new
                            {
                                checkResult = a.ExpectedStationIds,
                                items = alist.Where(x=>x.planId==a.OrderId).Select(n => new {
                                    checkAmount = n.FinishedCount,//盘点数量
                                    //periodSurplus = n.OrderId,
                                    profitLostAmount = n.MyProperty,//盈亏数量
                                    qualityStatus = n.qualityStatus,//质量状态
                                    stockId = n.WarehouseId//库存明细id
                                }).ToList(),
                                id = a.Id,
                                planId = a.OrderId,//盘点
                                supervisorId = a.InventoryId,
                                userId = a.WarehouseId,
                            };

                return query.FirstOrDefault();
            }
            catch (Exception)
            {

                throw new Exception();
            }
        }




        public object GetPdaQuanbu(string? Ordersn, int? status, int pageindex, int pagesize,out int totalcount)
        {
            //var list = Context.TStocktakingOrders.AsNoTracking();
            //if (planid!=null)
            //{
            //    list.Where(x => x.planId == planid);
            //}
            //list = list.FirstOrDefault();
            //return list.ToList();


            try
            {
                int dd = 3;
                int c = 5;
                //string uname = HttpContext.User.FindFirstValue("UserName");
                //string runame = HttpContext.User.FindFirstValue("RealName");
                //int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                var alist = Context.TStocktakingOrders.AsQueryable();//盘点订单
                var blist = Context.TStocktakingOrderDetails.AsQueryable();//盘点单号
                var clist = Context.TInventories.AsQueryable();//库区
                var dlist = Context.TWarehouses.AsQueryable();//库房
                var users = Context.TUsers.AsQueryable();//用户
                var query = from a in blist

                            where a.Status==status
                            select new
                            {
                                id = a.Id,
                                Ordersn=a.OrderSn,

                                checkResult = a.ExpectedStationIds,
                                Status = a.Status,
                                planId = a.OrderId,//盘点danhao1
                                //planNumber = a.OrderSn,//盘点计划单号
                                supervisorId = a.InventoryId,//监盘人id
                                userId = a.WarehouseId,///提交人id
                                items = alist.Where(x => x.planId == a.OrderId).Select(n => new
                                {
                                    batch=n.BatchNo,
                                    deptName=n.deptName,
                                    materialNorms=n.materialNorms,//规格型号
                                    materialCode =n.materialCode,//物料编码
                                    storeLocationRemark=n.storeLocationRemark,//存放库位描述
                                    storeName=n.WarehouseCode,//仓库名称
                                    ParentPalletBarcode = clist.FirstOrDefault(x => x.LocationId == Convert.ToInt32(n.PlanType) && x.MaterialName == n.MaterialName).ParentPalletBarcode,//托盘
                                    LocationCode = clist.FirstOrDefault(x => x.LocationId == Convert.ToInt32(n.PlanType) && x.MaterialName == n.MaterialName).LocationCode,//仓位名称
                                    materialName = n.MaterialName,//物料名称
                                    stockCount=n.FinishedCount,//库存数量
                                    checkAmount = n.FinishedCount,//盘点数量
                                    //periodSurplus = n.OrderId,
                                    profitLostAmount = n.MyProperty,//盈亏数量
                                    qualityStatus = n.qualityStatus,//质量状态
                                    stockId = n.WarehouseId,//库存明细id
                                    CreateUserId=n.CreateUserId,
                                    SubmitUserId=n.SubmitUserId,
                                    supervisorname = users.FirstOrDefault(x=>x.Id==n.CreateUserId).UserName,//监盘人名称
                                    username = users.FirstOrDefault(x => x.Id == n.SubmitUserId).UserName,//提交人名称
                                }).ToList(),
                                
                            };
                if (!string.IsNullOrEmpty(Ordersn))
                {
                    query = query.Where(x => x.Ordersn.Contains(Ordersn));
                }
                if (status!=-1)
                {
                    query = query.Where(x => x.Status == status);
                }
               
                

                query = query.Skip((pageindex - 1) * pagesize).Take(pagesize);
                totalcount = query.Count();
                //pagesize =query.Select(x=>x.id).Max();
                return query.ToList();
                //return query;
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }



        }
}
